package com.buaa.divinationmaster;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import com.buaa.divinationmaster.algorithm.TarotAlgorithm;
import com.buaa.divinationmaster.model.TarotCard;
import com.buaa.divinationmaster.utils.ScreenAdaptationUtil;

import java.util.List;

/**
 * 塔罗牌占卜页面
 * 根据需求文档实现完整的塔罗牌占卜流程：
 * 1. 输入问题
 * 2. 选择牌阵（单张/三张/五张/凯尔特十字）
 * 3. 互动抽牌（网格选择）
 * 4. 3D翻牌动画
 * 5. 逐张解读
 * 6. 综合建议
 */
public class TarotActivity extends AppCompatActivity {
    
    private EditText etQuestion;
    private CardView cardOneCard, cardThreeCard, cardFiveCard, cardCelticCross;
    private Button btnStartReading;
    
    private TarotAlgorithm.SpreadType selectedSpread = TarotAlgorithm.SpreadType.THREE_CARD; // 默认三张牌
    private List<TarotCard> tarotDeck;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tarot);
        
        // 应用屏幕适配
        ScreenAdaptationUtil.applyScreenAdaptation(this);
        
        setupToolbar();
        initViews();
        setupSpreadSelection();
        initializeTarotDeck();
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("塔罗牌占卜");
        }
    }
    
    private void initViews() {
        etQuestion = findViewById(R.id.etQuestion);
        cardOneCard = findViewById(R.id.cardOneCard);
        cardThreeCard = findViewById(R.id.cardThreeCard);
        cardFiveCard = findViewById(R.id.cardFiveCard);
        cardCelticCross = findViewById(R.id.cardCelticCross);
        btnStartReading = findViewById(R.id.btnStartReading);
        
        // 设置开始占卜按钮点击事件
        btnStartReading.setOnClickListener(v -> startTarotReading());
    }
    
    private void setupSpreadSelection() {
        // 设置牌阵选择点击事件
        cardOneCard.setOnClickListener(v -> selectSpread(TarotAlgorithm.SpreadType.ONE_CARD, cardOneCard));
        cardThreeCard.setOnClickListener(v -> selectSpread(TarotAlgorithm.SpreadType.THREE_CARD, cardThreeCard));
        cardFiveCard.setOnClickListener(v -> selectSpread(TarotAlgorithm.SpreadType.FIVE_CARD, cardFiveCard));
        cardCelticCross.setOnClickListener(v -> selectSpread(TarotAlgorithm.SpreadType.CELTIC_CROSS, cardCelticCross));
        
        // 默认选中三张牌
        selectSpread(TarotAlgorithm.SpreadType.THREE_CARD, cardThreeCard);
    }
    
    private void selectSpread(TarotAlgorithm.SpreadType spreadType, CardView selectedCard) {
        // 重置所有卡片状态
        resetSpreadCards();
        
        // 设置选中状态
        selectedSpread = spreadType;
        selectedCard.setCardBackgroundColor(getColor(R.color.accent_gold_variant));
        selectedCard.setAlpha(1.0f);
        
        // 更新按钮文本
        btnStartReading.setText("开始 " + spreadType.getName() + " 占卜");
    }
    
    private void initializeTarotDeck() {
        // 初始化78张塔罗牌库
        tarotDeck = TarotAlgorithm.createStandardDeck();
    }
    
    private void resetSpreadCards() {
        CardView[] cards = {cardOneCard, cardThreeCard, cardFiveCard, cardCelticCross};
        for (CardView card : cards) {
            card.setCardBackgroundColor(getColor(R.color.surface_dark));
            card.setAlpha(0.7f);
        }
    }
    
    private void startTarotReading() {
        String question = etQuestion.getText().toString().trim();
        
        if (question.isEmpty()) {
            etQuestion.setError("请输入您想占卜的问题");
            etQuestion.requestFocus();
            return;
        }
        
        // 执行塔罗牌占卜
        TarotAlgorithm.TarotReading reading = TarotAlgorithm.performReading(question, selectedSpread, tarotDeck);
        
        // 跳转到结果展示页面
        Intent intent = new Intent(this, TarotResultActivity.class);
        intent.putExtra("question", question);
        intent.putExtra("spreadType", selectedSpread.name());
        intent.putExtra("interpretation", reading.getInterpretation());
        intent.putExtra("timestamp", reading.getTimestamp());
        
        // 传递抽到的牌信息
        StringBuilder cardsInfo = new StringBuilder();
        for (int i = 0; i < reading.getCards().size(); i++) {
            TarotAlgorithm.DrawnCard drawnCard = reading.getCards().get(i);
            if (i > 0) cardsInfo.append("|");
            cardsInfo.append(drawnCard.getCard().getId()).append(",")
                    .append(drawnCard.isReversed()).append(",")
                    .append(drawnCard.getPositionMeaning());
        }
        intent.putExtra("cards", cardsInfo.toString());
        
        startActivity(intent);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
